import { Button, Input, Popup } from '@nutui/nutui-react-taro'
import { Image, ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import React, { useState } from 'react'
import Card from '../../components/card'
import Layout from '../../components/layout'
import { THEME_COLORS } from '../../constants'
import './index.less'

// 接口定义
interface Package {
  id: string
  name: string
  description: string
  image: string
}

interface Style {
  id: string
  name: string
  description: string
  image: string
  features: string[]
}

interface ColorScheme {
  id: string
  name: string
  description: string
  colors: string[]
  price: string
}

interface SpaceSize {
  building: string
  interior: string
}

interface SubCategoryOption {
  id: string
  name: string
  brand: string
  model: string
  price: string
  description: string
  image: string
}

interface SubCategory {
  id: string
  name: string
  current: string
  options: SubCategoryOption[]
}

const PackageSelection: React.FC = () => {
  // 状态管理
  const [selectedPackage, setSelectedPackage] = useState<string>('basic')
  const [selectedStyle, setSelectedStyle] = useState<string>('modern')
  const [selectedColor, setSelectedColor] = useState<string>('neutral')
  const [spaceSize, setSpaceSize] = useState<SpaceSize>({ building: '89', interior: '75' })

  // 模态框状态
  const [showStyleModal, setShowStyleModal] = useState<boolean>(false)
  const [showSizeModal, setShowSizeModal] = useState<boolean>(false)
  const [showColorModal, setShowColorModal] = useState<boolean>(false)
  const [showCustomizationModal, setShowCustomizationModal] = useState<boolean>(false)

  // 定制相关状态
  const [currentCustomizingCategory, setCurrentCustomizingCategory] = useState<string>('')
  const [selectedCategoryOptions, setSelectedCategoryOptions] = useState<{ [key: string]: string[] }>({})
  const [expandedSubCategories, setExpandedSubCategories] = useState<{ [key: string]: string[] }>({})
  const [showCategoryCustomizeButtons, setShowCategoryCustomizeButtons] = useState<boolean>(false)

  // 数据定义
  const packages: Package[] = [
    {
      id: 'basic',
      name: '精选套餐',
      description: '基础建材升级，包含多种高品质选择。',
      image: 'https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=400&h=300&fit=crop&crop=center',
    },
    {
      id: 'premium',
      name: '豪华套餐',
      description: '全面升级，包含高端建材和设计服务。',
      image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400&h=300&fit=crop&crop=center',
    },
    {
      id: 'custom',
      name: '定制套餐',
      description: '根据您的需求定制，包含个性化设计和高级建材。',
      image: 'https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=400&h=300&fit=crop&crop=center',
    },
  ]

  const styles: Style[] = [
    {
      id: 'modern',
      name: '现代简约',
      description: '简洁大方，注重功能性',
      image: 'https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=400&h=300&fit=crop&crop=center',
      features: ['简洁线条', '中性色调', '功能性家具', '充足采光'],
    },
    {
      id: 'nordic',
      name: '北欧风格',
      description: '自然清新，温馨舒适',
      image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400&h=300&fit=crop&crop=center',
      features: ['木质元素', '白色基调', '自然材质', '温馨氛围'],
    },
    {
      id: 'chinese',
      name: '中式风格',
      description: '传统韵味，典雅庄重',
      image: 'https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=400&h=300&fit=crop&crop=center',
      features: ['传统元素', '深色木材', '对称布局', '文化内涵'],
    },
    {
      id: 'european',
      name: '欧式风格',
      description: '奢华典雅，浪漫精致',
      image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400&h=300&fit=crop&crop=center',
      features: ['华丽装饰', '曲线设计', '精致细节', '贵族气质'],
    },
  ]

  const colorSchemes: ColorScheme[] = [
    {
      id: 'neutral',
      name: '中性色调',
      description: '米白、浅灰、原木色',
      colors: ['#F5F5F5', '#E0E0E0', '#D2B48C'],
      price: '¥0',
    },
    {
      id: 'warm',
      name: '暖色调',
      description: '米黄、暖灰、咖啡色',
      colors: ['#FFF8DC', '#F5DEB3', '#8B4513'],
      price: '+¥200',
    },
    {
      id: 'cool',
      name: '冷色调',
      description: '浅蓝、冷灰、白色',
      colors: ['#E6F3FF', '#B0C4DE', '#FFFFFF'],
      price: '+¥150',
    },
    {
      id: 'vibrant',
      name: '活力色调',
      description: '彩色搭配，个性鲜明',
      colors: ['#FFE4E1', '#E0FFFF', '#F0E68C'],
      price: '+¥500',
    },
  ]

  // 定制类目数据 - 根据Web版本完整还原
  const getCategorySubCategories = (categoryType: string): SubCategory[] => {
    const subCategories = {
      basic: [
        {
          id: 'wall_paint',
          name: '墙面翻新',
          current: '立邦 Nippon Paint',
          options: [
            {
              id: 'wall_paint_basic',
              name: '墙面翻新',
              brand: '立邦',
              model: 'Nippon Paint',
              price: '¥45/平米',
              description: '专业墙面翻新服务，包含基层处理、腻子找平、底漆涂刷、面漆涂刷',
              image: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'wall_paint_premium',
              name: '墙面翻新',
              brand: '多乐士',
              model: 'Dulux',
              price: '¥65/平米',
              description: '高端墙面翻新服务，防霉抗菌，环保无味',
              image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'wall_paint_luxury',
              name: '墙面翻新',
              brand: '芬琳',
              model: 'Tikkurila',
              price: '¥85/平米',
              description: '进口高端墙面翻新，色彩丰富，持久耐用',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'floor',
          name: '地面铺设',
          current: '马可波罗 Marco Polo',
          options: [
            {
              id: 'floor_basic',
              name: '地面铺设',
              brand: '马可波罗',
              model: 'Marco Polo',
              price: '¥120/平米',
              description: '瓷砖地面铺设，包含找平、防水、铺贴、美缝',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'floor_premium',
              name: '地面铺设',
              brand: '东鹏',
              model: 'Dongpeng',
              price: '¥85/平米',
              description: '高品质地砖，耐磨防滑，多种花色可选',
              image: 'https://images.unsplash.com/photo-1505693416388-ac5ce068fe85?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'floor_luxury',
              name: '地面铺设',
              brand: '诺贝尔',
              model: 'Nobel',
              price: '¥150/平米',
              description: '进口瓷砖，质感细腻，高端大气',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'ceiling',
          name: '吊顶安装',
          current: '欧普 OPPLE',
          options: [
            {
              id: 'ceiling_basic',
              name: '吊顶安装',
              brand: '欧普',
              model: 'OPPLE',
              price: '¥80/平米',
              description: '集成吊顶安装，包含龙骨安装、扣板安装、灯具安装',
              image: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'ceiling_premium',
              name: '吊顶安装',
              brand: '雷士',
              model: 'NVC',
              price: '¥100/平米',
              description: '高端集成吊顶，智能照明，节能环保',
              image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      plumbing: [
        {
          id: 'circuit',
          name: '电路改造',
          current: '德力西 DELIXI',
          options: [
            {
              id: 'circuit_basic',
              name: '电路改造',
              brand: '德力西',
              model: 'DELIXI',
              price: '¥35/平米',
              description: '电路改造服务，包含开槽、布线、安装开关插座',
              image: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'circuit_premium',
              name: '电路改造',
              brand: '施耐德',
              model: 'Schneider',
              price: '¥50/平米',
              description: '高端电路改造，智能开关，安全可靠',
              image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'circuit_luxury',
              name: '电路改造',
              brand: '西门子',
              model: 'Siemens',
              price: '¥65/平米',
              description: '进口电路系统，智能家居布线，品质保证',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'water',
          name: '水路改造',
          current: '伟星 Weixing',
          options: [
            {
              id: 'water_basic',
              name: '水路改造',
              brand: '伟星',
              model: 'Weixing',
              price: '¥40/平米',
              description: '水路改造服务，包含开槽、布管、安装水龙头',
              image: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'water_premium',
              name: '水路改造',
              brand: '日丰',
              model: 'Rifeng',
              price: '¥55/平米',
              description: '高端水路改造，PPR管材，耐高温耐压',
              image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      material: [
        {
          id: 'tile',
          name: '地砖',
          current: '东鹏 Dongpeng',
          options: [
            {
              id: 'tile_basic',
              name: '地砖',
              brand: '东鹏',
              model: 'Dongpeng',
              price: '¥85/平米',
              description: '高品质地砖，耐磨防滑，多种花色可选',
              image: 'https://images.unsplash.com/photo-1505693416388-ac5ce068fe85?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'tile_premium',
              name: '地砖',
              brand: '马可波罗',
              model: 'Marco Polo',
              price: '¥120/平米',
              description: '瓷砖地面铺设，包含找平、防水、铺贴、美缝',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'tile_luxury',
              name: '地砖',
              brand: '诺贝尔',
              model: 'Nobel',
              price: '¥150/平米',
              description: '进口瓷砖，质感细腻，高端大气',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'sanitary',
          name: '洁具',
          current: '科勒 Kohler',
          options: [
            {
              id: 'sanitary_basic',
              name: '洁具',
              brand: '科勒',
              model: 'Kohler',
              price: '¥1200/台',
              description: '高品质洁具，节水环保，多种款式可选',
              image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'sanitary_premium',
              name: '洁具',
              brand: '汉斯格雅',
              model: 'Hansgrohe',
              price: '¥1800/台',
              description: '德国进口洁具，智能控制，节水环保',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      labor: [
        {
          id: 'labor',
          name: '人工费',
          current: '专业团队',
          options: [
            {
              id: 'labor_basic',
              name: '人工费',
              brand: '专业团队',
              model: 'Standard',
              price: '¥60/平米',
              description: '专业施工团队，经验丰富，质量保证',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'labor_premium',
              name: '人工费',
              brand: '高级团队',
              model: 'Premium',
              price: '¥80/平米',
              description: '高级技工团队，专业技能，品质保证',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'auxiliary',
          name: '辅材费',
          current: '优质辅材',
          options: [
            {
              id: 'auxiliary_basic',
              name: '辅材费',
              brand: '优质辅材',
              model: 'Standard',
              price: '¥25/平米',
              description: '优质辅材，包含胶水、螺丝、密封胶等',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'auxiliary_premium',
              name: '辅材费',
              brand: '高端辅材',
              model: 'Premium',
              price: '¥35/平米',
              description: '高端辅材，环保无毒，品质保证',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      furniture: [
        {
          id: 'table',
          name: '餐桌',
          current: '顾家家居 KUKA',
          options: [
            {
              id: 'table_basic',
              name: '餐桌',
              brand: '顾家家居',
              model: 'KUKA',
              price: '¥2800/台',
              description: '实木餐桌，环保健康，多种尺寸可选',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'table_premium',
              name: '餐桌',
              brand: '曲美',
              model: 'QM',
              price: '¥3500/台',
              description: '现代简约餐桌，设计感强，品质保证',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'wardrobe',
          name: '衣柜',
          current: '索菲亚 Sogal',
          options: [
            {
              id: 'wardrobe_basic',
              name: '衣柜',
              brand: '索菲亚',
              model: 'Sogal',
              price: '¥4500/台',
              description: '定制衣柜，空间利用率高，多种款式可选',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'wardrobe_premium',
              name: '衣柜',
              brand: '欧派',
              model: 'OPPEIN',
              price: '¥5500/台',
              description: '高端定制衣柜，智能收纳，环保板材',
              image: 'https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      appliance: [
        {
          id: 'refrigerator',
          name: '冰箱',
          current: '海尔 Haier',
          options: [
            {
              id: 'refrigerator_basic',
              name: '冰箱',
              brand: '海尔',
              model: 'Haier',
              price: '¥2800/台',
              description: '节能冰箱，大容量存储，智能温控',
              image: 'https://images.unsplash.com/photo-1571175443880-49e1d25b2bc5?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'refrigerator_premium',
              name: '冰箱',
              brand: '美的',
              model: 'Midea',
              price: '¥3500/台',
              description: '智能冰箱，变频节能，大容量设计',
              image: 'https://images.unsplash.com/photo-1571175443880-49e1d25b2bc5?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'tv',
          name: '电视',
          current: '小米 MI',
          options: [
            {
              id: 'tv_basic',
              name: '电视',
              brand: '小米',
              model: 'MI',
              price: '¥2200/台',
              description: '智能电视，4K高清，多种尺寸可选',
              image: 'https://images.unsplash.com/photo-1593359677879-a4bb92f829d1?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'tv_premium',
              name: '电视',
              brand: '海信',
              model: 'Hisense',
              price: '¥3000/台',
              description: '4K智能电视，HDR显示，音质出色',
              image: 'https://images.unsplash.com/photo-1593359677879-a4bb92f829d1?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      service: [
        {
          id: 'design_service',
          name: '专业设计服务',
          current: '设计团队',
          options: [
            {
              id: 'design_service',
              name: '专业设计服务',
              brand: '设计团队',
              model: 'Standard',
              price: '¥1500/项',
              description: '专业室内设计师提供设计方案，包含效果图、施工图',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'design_premium',
              name: '专业设计服务',
              brand: '高级设计团队',
              model: 'Premium',
              price: '¥2500/项',
              description: '资深设计师一对一服务，3D效果图，全程跟踪',
              image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
        {
          id: 'supervision',
          name: '工程监理服务',
          current: '监理团队',
          options: [
            {
              id: 'supervision',
              name: '工程监理服务',
              brand: '监理团队',
              model: 'Standard',
              price: '¥800/项',
              description: '专业工程监理，全程监督施工质量，确保工程进度',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'supervision_premium',
              name: '工程监理服务',
              brand: '高级监理团队',
              model: 'Premium',
              price: '¥1200/项',
              description: '资深监理师，专业检测设备，质量保证',
              image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
      warranty: [
        {
          id: 'warranty_standard',
          name: '标准保修',
          current: '保修服务',
          options: [
            {
              id: 'warranty_standard',
              name: '标准保修',
              brand: '保修服务',
              model: 'Standard',
              price: '¥0/项',
              description: '标准保修服务，保修期1年',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'warranty_extended',
              name: '延长保修',
              brand: '保修服务',
              model: 'Extended',
              price: '¥200/项',
              description: '延长保修服务，保修期延长至2年',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
            {
              id: 'warranty_lifetime',
              name: '终身保修',
              brand: '保修服务',
              model: 'Lifetime',
              price: '¥500/项',
              description: '终身保修服务，终身免费维护',
              image: 'https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=300&h=200&fit=crop&crop=center',
            },
          ],
        },
      ],
    }
    return (subCategories[categoryType] || []) as SubCategory[]
  }

  // 根据选择的套餐获取对应的报价数据
  const getPackageQuotation = (packageId: string) => {
    const quotations = {
      basic: {
        categories: [
          {
            category: '基础工程',
            type: 'basic',
            items: [
              { name: '墙面翻新（含环保乳胶漆）', price: '¥12,000' },
              { name: '地面铺设（强化复合地板）', price: '¥8,000' },
            ],
            total: '¥20,000',
          },
          {
            category: '水电改造',
            type: 'plumbing',
            items: [{ name: '水电改造（国标电线、PPR水管）', price: '¥6,000' }],
            total: '¥6,000',
          },
          {
            category: '材料费',
            type: 'material',
            items: [
              { name: '厨房墙地面（品牌瓷砖）', price: '¥5,000' },
              { name: '卫生间墙地面（品牌瓷砖）', price: '¥4,500' },
              { name: '基础洁具（箭牌/九牧）', price: '¥3,500' },
            ],
            total: '¥13,000',
          },
          {
            category: '人工及辅材',
            type: 'labor',
            items: [{ name: '人工及辅材费', price: '¥10,000' }],
            total: '¥10,000',
          },
          {
            category: '家具',
            type: 'furniture',
            items: [],
            total: '¥0',
          },
          {
            category: '家电',
            type: 'appliance',
            items: [],
            total: '¥0',
          },
          {
            category: '附加服务',
            type: 'service',
            items: [],
            total: '¥0',
          },
          {
            category: '保修标准',
            type: 'warranty',
            items: [],
            total: '¥0',
          },
        ],
        total: '¥49,000',
      },
      premium: {
        categories: [
          {
            category: '基础工程',
            type: 'basic',
            items: [
              { name: '墙面翻新（高端乳胶漆）', price: '¥18,000' },
              { name: '地面铺设（实木复合地板）', price: '¥15,000' },
            ],
            total: '¥33,000',
          },
          {
            category: '水电改造',
            type: 'plumbing',
            items: [{ name: '水电改造（德系标准）', price: '¥12,000' }],
            total: '¥12,000',
          },
          {
            category: '材料费',
            type: 'material',
            items: [
              { name: '厨房墙地面（进口瓷砖）', price: '¥12,000' },
              { name: '卫生间墙地面（进口瓷砖）', price: '¥10,000' },
              { name: '高端洁具（科勒/汉斯格雅）', price: '¥8,000' },
            ],
            total: '¥30,000',
          },
          {
            category: '人工及辅材',
            type: 'labor',
            items: [{ name: '人工及辅材费', price: '¥18,000' }],
            total: '¥18,000',
          },
          {
            category: '家具',
            type: 'furniture',
            items: [],
            total: '¥0',
          },
          {
            category: '家电',
            type: 'appliance',
            items: [],
            total: '¥0',
          },
          {
            category: '附加服务',
            type: 'service',
            items: [],
            total: '¥0',
          },
          {
            category: '保修标准',
            type: 'warranty',
            items: [],
            total: '¥0',
          },
        ],
        total: '¥93,000',
      },
      custom: {
        categories: [
          {
            category: '基础工程',
            type: 'basic',
            items: [
              { name: '墙面翻新（定制乳胶漆）', price: '¥25,000' },
              { name: '地面铺设（实木地板）', price: '¥22,000' },
            ],
            total: '¥47,000',
          },
          {
            category: '水电改造',
            type: 'plumbing',
            items: [{ name: '水电改造（智能家居布线）', price: '¥20,000' }],
            total: '¥20,000',
          },
          {
            category: '材料费',
            type: 'material',
            items: [
              { name: '厨房墙地面（定制瓷砖）', price: '¥20,000' },
              { name: '卫生间墙地面（定制瓷砖）', price: '¥18,000' },
              { name: '顶级洁具（杜拉维特/唯宝）', price: '¥15,000' },
            ],
            total: '¥53,000',
          },
          {
            category: '人工及辅材',
            type: 'labor',
            items: [{ name: '人工及辅材费', price: '¥25,000' }],
            total: '¥25,000',
          },
          {
            category: '家具',
            type: 'furniture',
            items: [],
            total: '¥0',
          },
          {
            category: '家电',
            type: 'appliance',
            items: [],
            total: '¥0',
          },
          {
            category: '附加服务',
            type: 'service',
            items: [],
            total: '¥0',
          },
          {
            category: '保修标准',
            type: 'warranty',
            items: [],
            total: '¥0',
          },
        ],
        total: '¥145,000',
      },
    }
    return quotations[packageId] || quotations.basic
  }

  // 计算类目总价
  const calculateCategoryTotal = (categoryType: string): number => {
    const selectedOptions = getSelectedOptions(categoryType)
    const subCategories = getCategorySubCategories(categoryType)

    return selectedOptions.reduce((total, optionId) => {
      // 在所有子类中查找选项
      for (const subCategory of subCategories) {
        const option = subCategory.options.find((opt) => opt.id === optionId)
        if (option) {
          // 处理单价格式，如 "¥45/平米" -> 45
          const priceStr = option.price.replace(/[¥,]/g, '').split('/')[0]
          return total + (parseInt(priceStr) || 0)
        }
      }
      return total
    }, 0)
  }

  // 获取当前类目已选择的选项
  const getSelectedOptions = (categoryType: string): string[] => {
    return selectedCategoryOptions[categoryType] || []
  }

  // 获取当前类目已展开的子类
  const getExpandedSubCategories = (categoryType: string): string[] => {
    return expandedSubCategories[categoryType] || []
  }

  // 事件处理
  const handleSelectPackage = (pkgId: string) => {
    setSelectedPackage(pkgId)
  }

  const handleStyleSelect = (styleId: string) => {
    setSelectedStyle(styleId)
    setShowStyleModal(false)
  }

  const handleColorSelect = (colorId: string) => {
    setSelectedColor(colorId)
    setShowColorModal(false)
  }

  const handleSizeChange = (field: keyof SpaceSize, value: string) => {
    setSpaceSize((prev) => ({ ...prev, [field]: value }))
  }

  const handleConfirm = () => {
    // 确认选择，跳转到下一步
    Taro.showToast({
      title: '确认成功',
      icon: 'success',
    })
    // Taro.navigateTo({ url: '/pages/quick-appointment/index' })
  }

  // 处理总"去定制"按钮点击
  const handleMainCustomizeClick = () => {
    setShowCategoryCustomizeButtons(true)
  }

  // 处理类目定制按钮点击
  const handleCategoryCustomize = (categoryType: string) => {
    setCurrentCustomizingCategory(categoryType)
    setShowCustomizationModal(true)
  }

  // 处理子类展开/收起
  const handleSubCategoryToggle = (categoryType: string, subCategoryId: string) => {
    setExpandedSubCategories((prev) => {
      const currentExpanded = prev[categoryType] || []
      const isExpanded = currentExpanded.includes(subCategoryId)

      if (isExpanded) {
        return {
          ...prev,
          [categoryType]: currentExpanded.filter((id) => id !== subCategoryId),
        }
      } else {
        return {
          ...prev,
          [categoryType]: [...currentExpanded, subCategoryId],
        }
      }
    })
  }

  // 处理类目选项选择（单选）
  const handleCategoryOptionToggle = (categoryType: string, optionId: string) => {
    setSelectedCategoryOptions((prev) => {
      const currentOptions = prev[categoryType] || []
      const isSelected = currentOptions.includes(optionId)

      if (isSelected) {
        // 如果已选中，则取消选择
        return {
          ...prev,
          [categoryType]: [],
        }
      } else {
        // 单选：只保留当前选中的选项
        return {
          ...prev,
          [categoryType]: [optionId],
        }
      }
    })
  }

  // 获取当前选中的数据
  const selectedStyleData = styles.find((style) => style.id === selectedStyle)
  const selectedColorData = colorSchemes.find((scheme) => scheme.id === selectedColor)

  return (
    <Layout showTabBar={false} title='套餐选择'>
      <ScrollView className='page-content' scrollY>
        {/* 1. 风格选择 */}
        <View className='selection-section'>
          <View className='section-header'>
            <Text className='section-title'>风格选择</Text>
            <View className='modify-button' onClick={() => setShowStyleModal(true)}>
              <Text style={{ color: THEME_COLORS.primary }}>去修改</Text>
              <Text className='chevron-icon'>›</Text>
            </View>
          </View>
          <Card padding='md' rounded='lg' shadow='sm'>
            <View className='style-info'>
              <Image className='style-image' src={selectedStyleData?.image || ''} mode='aspectFill' />
              <View className='style-details'>
                <Text className='style-name'>{selectedStyleData?.name}</Text>
                <Text className='style-description'>{selectedStyleData?.description}</Text>
              </View>
            </View>
          </Card>
        </View>

        {/* 2. 色彩方案 */}
        <View className='selection-section'>
          <View className='section-header'>
            <Text className='section-title'>色彩方案</Text>
            <View className='modify-button' onClick={() => setShowColorModal(true)}>
              <Text style={{ color: THEME_COLORS.primary }}>去修改</Text>
              <Text className='chevron-icon'>›</Text>
            </View>
          </View>
          <Card padding='md' rounded='lg' shadow='sm'>
            <View className='color-scheme'>
              <View className='color-header'>
                <Text className='color-name'>{selectedColorData?.name}</Text>
                <Text className='color-price' style={{ color: THEME_COLORS.primary }}>
                  {selectedColorData?.price}
                </Text>
              </View>
              <Text className='color-description'>{selectedColorData?.description}</Text>
              <View className='color-palette'>
                {selectedColorData?.colors.map((color, index) => (
                  <View key={index} className='color-dot' style={{ backgroundColor: color }} />
                ))}
              </View>
            </View>
          </Card>
        </View>

        {/* 3. 空间尺寸 */}
        <View className='selection-section'>
          <View className='section-header'>
            <Text className='section-title'>空间尺寸</Text>
            <View className='modify-button' onClick={() => setShowSizeModal(true)}>
              <Text style={{ color: THEME_COLORS.primary }}>去修改</Text>
              <Text className='chevron-icon'>›</Text>
            </View>
          </View>
          <Card padding='md' rounded='lg' shadow='sm'>
            <View className='space-info'>
              <Text className='space-item'>建筑面积：{spaceSize.building}m²</Text>
              <Text className='space-item'>套内面积：{spaceSize.interior}m²</Text>
            </View>
          </Card>
        </View>

        {/* 4. 套餐选择 */}
        <View className='selection-section'>
          <View className='section-header'>
            <Text className='section-title'>套餐选择</Text>
          </View>
          <ScrollView className='package-scroll' scrollX>
            <View className='package-cards'>
              {packages.map((pkg) => (
                <View
                  key={pkg.id}
                  className={`package-card ${selectedPackage === pkg.id ? 'selected' : ''}`}
                  style={{
                    borderColor: selectedPackage === pkg.id ? THEME_COLORS.primary : 'transparent',
                  }}
                  onClick={() => handleSelectPackage(pkg.id)}>
                  <Image className='package-image' src={pkg.image} mode='aspectFill' />
                  <View className='package-content'>
                    <Text className='package-name'>{pkg.name}</Text>
                    <Text className='package-description'>{pkg.description}</Text>
                  </View>
                </View>
              ))}
            </View>
          </ScrollView>
        </View>

        {/* 5. 项目报价 */}
        <View className='quotation-section'>
          <View className='section-header'>
            <Text className='section-title'>项目报价</Text>
          </View>
          <Card padding='md' rounded='lg' shadow='sm'>
            <View className='quotation-header'>
              <Text className='header-label'>费用项</Text>
              <View className='header-action'>
                {!showCategoryCustomizeButtons && (
                  <View className='modify-button' onClick={handleMainCustomizeClick}>
                    <Text style={{ color: THEME_COLORS.primary }}>去定制</Text>
                    <Text className='chevron-icon'>›</Text>
                  </View>
                )}
              </View>
            </View>

            <View className='quotation-categories'>
              {getPackageQuotation(selectedPackage)
                .categories.filter((category) => {
                  // 如果还没有点击总"去定制"按钮，过滤掉价格为0的类别
                  if (!showCategoryCustomizeButtons) {
                    return category.total !== '¥0' && category.total !== '0'
                  }
                  return true
                })
                .map((category, categoryIndex) => {
                  const selectedOptions = getSelectedOptions(category.type)
                  const subCategories = getCategorySubCategories(category.type)
                  const customTotal = calculateCategoryTotal(category.type)
                  const hasCustomOptions = selectedOptions.length > 0

                  return (
                    <View key={categoryIndex} className='category-item'>
                      <View className='category-header'>
                        <View className='category-title-row'>
                          <Text className='category-name'>{category.category}</Text>
                          {showCategoryCustomizeButtons && (
                            <View
                              className='customize-button'
                              onClick={() => handleCategoryCustomize(category.type)}>
                              <Text style={{ color: THEME_COLORS.primary, fontSize: '12px' }}>去定制</Text>
                              <Text className='chevron-icon' style={{ fontSize: '14px' }}>
                                ›
                              </Text>
                            </View>
                          )}
                        </View>
                        <Text className='category-total'>
                          {hasCustomOptions ? `¥${customTotal.toLocaleString()}` : category.total}
                        </Text>
                      </View>
                      <View className='category-items'>
                        {hasCustomOptions
                          ? selectedOptions.map((optionId) => {
                              let option: SubCategoryOption | undefined
                              for (const subCategory of subCategories) {
                                option = subCategory.options.find((opt) => opt.id === optionId)
                                if (option) break
                              }
                              return option ? (
                                <View key={optionId} className='item-row'>
                                  <Text className='item-name'>{option.name}</Text>
                                  <Text className='item-price'>{option.price}</Text>
                                </View>
                              ) : null
                            })
                          : category.items.map((item, itemIndex) => (
                              <View key={itemIndex} className='item-row'>
                                <Text className='item-name'>{item.name}</Text>
                                <Text className='item-price'>{item.price}</Text>
                              </View>
                            ))}
                      </View>
                    </View>
                  )
                })}
            </View>

            <View className='quotation-total'>
              <View className='total-row'>
                <Text className='total-label'>总计</Text>
                <Text className='total-amount' style={{ color: THEME_COLORS.primary }}>
                  {(() => {
                    const currentQuotation = getPackageQuotation(selectedPackage)
                    const baseTotal = parseInt(currentQuotation.total.replace(/[¥,]/g, ''))
                    const customTotal = ['basic', 'plumbing', 'material', 'labor', 'furniture', 'appliance', 'service', 'warranty'].reduce(
                      (total, categoryType) => {
                        const selectedOptions = getSelectedOptions(categoryType)
                        if (selectedOptions.length > 0) {
                          return total + calculateCategoryTotal(categoryType)
                        }
                        return total
                      },
                      0
                    )
                    return `¥${(baseTotal + customTotal).toLocaleString()}`
                  })()}
                </Text>
              </View>
              <Text className='total-note'>*此报价为估算价格，最终价格以实际测量和材料选择为准。</Text>
            </View>
          </Card>
        </View>
      </ScrollView>

      {/* 底部确认按钮 */}
      <View className='bottom-button'>
        <Button
          className='confirm-button'
          style={{
            background: THEME_COLORS.primary,
            color: '#fff',
          }}
          onClick={handleConfirm}>
          确认选择
        </Button>
      </View>

      {/* 风格选择模态框 */}
      <Popup visible={showStyleModal} position='bottom' onClose={() => setShowStyleModal(false)} style={{ height: '80vh' }}>
        <View className='modal-content'>
          <View className='modal-header'>
            <Text className='modal-title'>风格选择</Text>
            <View className='close-button' onClick={() => setShowStyleModal(false)}>
              ✕
            </View>
          </View>
          <ScrollView className='modal-body' scrollY>
            <View className='style-options'>
              {styles.map((style) => (
                <View key={style.id} className='style-option' onClick={() => handleStyleSelect(style.id)}>
                  <View className={`style-option-image ${selectedStyle === style.id ? 'selected' : ''}`}>
                    <Image src={style.image} mode='aspectFill' className='style-img' />
                    {selectedStyle === style.id && (
                      <View className='check-icon' style={{ backgroundColor: THEME_COLORS.primary }}>
                        ✓
                      </View>
                    )}
                  </View>
                  <Text className='style-option-name'>{style.name}</Text>
                  <Text className='style-option-description'>{style.description}</Text>
                </View>
              ))}
            </View>
          </ScrollView>
          <View className='modal-footer'>
            <Button
              className='modal-button'
              style={{ background: THEME_COLORS.primary }}
              onClick={() => setShowStyleModal(false)}>
              确认选择
            </Button>
          </View>
        </View>
      </Popup>

      {/* 尺寸修改模态框 */}
      <Popup visible={showSizeModal} position='bottom' onClose={() => setShowSizeModal(false)} style={{ height: '60vh' }}>
        <View className='modal-content'>
          <View className='modal-header'>
            <Text className='modal-title'>空间尺寸</Text>
            <View className='close-button' onClick={() => setShowSizeModal(false)}>
              ✕
            </View>
          </View>
          <View className='modal-body'>
            <View className='size-inputs'>
              <View className='input-group'>
                <Text className='input-label'>建筑面积 (m²)</Text>
                <Input
                  className='size-input'
                  value={spaceSize.building}
                  onChange={(value) => handleSizeChange('building', value)}
                  type='number'
                  placeholder='请输入建筑面积'
                />
              </View>
              <View className='input-group'>
                <Text className='input-label'>套内面积 (m²)</Text>
                <Input
                  className='size-input'
                  value={spaceSize.interior}
                  onChange={(value) => handleSizeChange('interior', value)}
                  type='number'
                  placeholder='请输入套内面积'
                />
              </View>
            </View>
          </View>
          <View className='modal-footer'>
            <Button className='modal-button' style={{ background: THEME_COLORS.primary }} onClick={() => setShowSizeModal(false)}>
              确认修改
            </Button>
          </View>
        </View>
      </Popup>

      {/* 色彩方案模态框 */}
      <Popup visible={showColorModal} position='bottom' onClose={() => setShowColorModal(false)} style={{ height: '70vh' }}>
        <View className='modal-content'>
          <View className='modal-header'>
            <Text className='modal-title'>色彩方案</Text>
            <View className='close-button' onClick={() => setShowColorModal(false)}>
              ✕
            </View>
          </View>
          <ScrollView className='modal-body' scrollY>
            <View className='color-options'>
              {colorSchemes.map((scheme) => (
                <View
                  key={scheme.id}
                  className={`color-option ${selectedColor === scheme.id ? 'selected' : ''}`}
                  style={{
                    borderColor: selectedColor === scheme.id ? THEME_COLORS.primary : '#e5e7eb',
                    backgroundColor: selectedColor === scheme.id ? `${THEME_COLORS.primary}10` : '#fff',
                  }}
                  onClick={() => handleColorSelect(scheme.id)}>
                  <View className='color-option-header'>
                    <Text className='color-option-name'>{scheme.name}</Text>
                    <Text className='color-option-price' style={{ color: THEME_COLORS.primary }}>
                      {scheme.price}
                    </Text>
                  </View>
                  <Text className='color-option-description'>{scheme.description}</Text>
                  <View className='color-option-palette'>
                    {scheme.colors.map((color, index) => (
                      <View key={index} className='color-option-dot' style={{ backgroundColor: color }} />
                    ))}
                  </View>
                </View>
              ))}
            </View>
          </ScrollView>
          <View className='modal-footer'>
            <Button className='modal-button' style={{ background: THEME_COLORS.primary }} onClick={() => setShowColorModal(false)}>
              确认选择
            </Button>
          </View>
        </View>
      </Popup>

      {/* 类目定制模态框 */}
      <Popup
        visible={showCustomizationModal}
        position='bottom'
        onClose={() => setShowCustomizationModal(false)}
        style={{ height: '90vh' }}>
        <View className='modal-content'>
          <View className='modal-header'>
            <Text className='modal-title'>
              {currentCustomizingCategory === 'basic' && '基础工程定制'}
              {currentCustomizingCategory === 'plumbing' && '水电改造定制'}
              {currentCustomizingCategory === 'material' && '材料费定制'}
              {currentCustomizingCategory === 'labor' && '人工及辅材定制'}
              {currentCustomizingCategory === 'furniture' && '家具定制'}
              {currentCustomizingCategory === 'appliance' && '家电定制'}
              {currentCustomizingCategory === 'service' && '附加服务定制'}
              {currentCustomizingCategory === 'warranty' && '保修标准定制'}
            </Text>
            <View className='close-button' onClick={() => setShowCustomizationModal(false)}>
              ✕
            </View>
          </View>
          <ScrollView className='modal-body' scrollY>
            <Text className='modal-tip'>
              {currentCustomizingCategory === 'basic' && '选择基础工程的具体项目和材料'}
              {currentCustomizingCategory === 'plumbing' && '选择水电改造的标准和材料'}
              {currentCustomizingCategory === 'material' && '选择各类装修材料'}
              {currentCustomizingCategory === 'labor' && '选择人工和辅材标准'}
              {currentCustomizingCategory === 'furniture' && '选择家具类型和品牌'}
              {currentCustomizingCategory === 'appliance' && '选择家电品牌和型号'}
              {currentCustomizingCategory === 'service' && '选择附加服务项目'}
              {currentCustomizingCategory === 'warranty' && '选择保修标准'}
            </Text>

            <View className='customization-list'>
              {getCategorySubCategories(currentCustomizingCategory).map((subCategory) => (
                <Card key={subCategory.id} padding='md' rounded='lg' shadow='sm' className='sub-category-card'>
                  <View className='sub-category-header'>
                    <Text className='sub-category-name'>{subCategory.name}</Text>
                    <View
                      className='toggle-button'
                      onClick={() => handleSubCategoryToggle(currentCustomizingCategory, subCategory.id)}>
                      <Text style={{ color: THEME_COLORS.primary }}>
                        {getExpandedSubCategories(currentCustomizingCategory).includes(subCategory.id) ? '收起' : '选择'}
                      </Text>
                    </View>
                  </View>
                  <Text className='sub-category-current'>当前: {subCategory.current}</Text>

                  {getExpandedSubCategories(currentCustomizingCategory).includes(subCategory.id) && (
                    <ScrollView className='options-scroll' scrollX>
                      <View className='option-cards'>
                        {subCategory.options.map((option) => {
                          const isSelected = getSelectedOptions(currentCustomizingCategory).includes(option.id)
                          return (
                            <View
                              key={option.id}
                              className='option-card'
                              style={{
                                borderColor: isSelected ? THEME_COLORS.primary : 'transparent',
                                backgroundColor: isSelected ? `${THEME_COLORS.primary}10` : '#f9fafb',
                              }}
                              onClick={() => handleCategoryOptionToggle(currentCustomizingCategory, option.id)}>
                              <Image src={option.image} mode='aspectFill' className='option-image' />
                              <View className='option-content'>
                                <Text className='option-name'>{option.name}</Text>
                                <Text className='option-brand'>
                                  {option.brand} {option.model}
                                </Text>
                                <Text className='option-description'>{option.description}</Text>
                                <View className='option-footer'>
                                  <Text className='option-price' style={{ color: THEME_COLORS.primary }}>
                                    {option.price}
                                  </Text>
                                  {isSelected && (
                                    <Text className='option-check' style={{ color: THEME_COLORS.primary }}>
                                      ✓
                                    </Text>
                                  )}
                                </View>
                              </View>
                            </View>
                          )
                        })}
                      </View>
                    </ScrollView>
                  )}
                </Card>
              ))}
            </View>
          </ScrollView>
          <View className='modal-footer'>
            <Button
              className='modal-button'
              style={{ background: THEME_COLORS.primary }}
              onClick={() => setShowCustomizationModal(false)}>
              确认定制
            </Button>
          </View>
        </View>
      </Popup>
    </Layout>
  )
}

export default PackageSelection
